package api

import (
	"ims/app/dao"
	"ims/app/model"
	"ims/tools"
	"ims/tools/response"
	"time"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

type login struct {
	Password string `p:"password"`
	Username string `p:"username"`
}

//查询 User 和 UserRole信息
func CheckKefuPass(username string, password string) (model.User, model.UserRole, bool) {
	var info model.User
	dao.User.Where(dao.User.Columns.Name, username).Scan(&info)

	var uRole model.UserRole

	if info.Name == "" || info.Password != tools.Md5(password) {
		return info, uRole, false
	}
	dao.UserRole.Where(dao.UserRole.Columns.Id, info.Id).Scan(&uRole)

	return info, uRole, true
}

//登陆表单验证 密码和 账号
func LoginCheckPass(r *ghttp.Request) {

	var form login
	r.Parse(&form)
	password := form.Password
	username := form.Username

	info, uRole, ok := CheckKefuPass(username, password)
	userinfo := make(map[string]interface{})
	if !ok {
		response.JsonResponse(r, g.Map{
			"code": 400,
			"msg":  "验证失败",
		})

	}
	userinfo["name"] = info.Name
	userinfo["kefu_id"] = info.Id
	userinfo["type"] = "kefu"
	if uRole.RoleId != 0 {
		userinfo["role_id"] = uRole.RoleId
	} else {
		userinfo["role_id"] = 2
	}
	userinfo["create_time"] = time.Now().Unix()

	token, _ := tools.MakeToken(userinfo)
	userinfo["ref_token"] = true
	refToken, _ := tools.MakeToken(userinfo)
	response.JsonResponse(r, g.Map{
		"code": 200,
		"msg":  "验证成功,正在跳转",
		"result": g.Map{
			"token":       token,
			"ref_token":   refToken,
			"create_time": userinfo["create_time"],
		},
	})
}

func CheckAuth(r *ghttp.Request) {
	id := r.GetString("kefu_id", 1)

	userinfo := dao.FindUserRole(r, id)
	response.JsonResponse(r, g.Map{
		"code": 200,
		"msg":  "验证成功",
		"result": g.Map{
			"avator":    userinfo.Avator,
			"name":      userinfo.Name,
			"role_name": userinfo.RoleName,
		},
	})
}
